;
(function() {
  new Vue({
    el: '#projectGl',
    data: {
      isExtenseFlag: false,
      keyWord: '',
      pageNums: [{name: '10', code: '10'}, {name: '15', code: '15'}, {name: '20', code: '20'}],
      limit: ['10'],
      page: 1,
      tbTitleWidth: {},
      listMenu: [{
          name: '待分派',
          code: 'WFP',
          num: '',
        },
        {
          name: '已分派',
          code: 'YFP',
          num: '',
        },
      ],
      listMenuArrActive: [],
      listObj: {
        expansionProjs: []
      },
      rperson: {
        ids: [],
        name: null,
        list: []
      },
      
      provinceId: [],
      cityId: [],
      areaId: [],
      channelCategoryCode: [],
      channelNameCode: [],
      columns: '#',
      orders: '#',
      provinceList: [],
      cityList: [],
      areaList: [],
      keyword: '',
      channelCateArr: [],
      channelNameArr: [],
      isShowPersonLayer: false,
      positionList: [],
      personList: [],
      isShowSelector: false,
      selectedMulItem:{sjIds:[],id:null,name:null},
      permissions: JSON.parse(window.localStorage.getItem('permissions')),
  

      	//自定义开始
			configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
			module: '#',
			headArr: [],
			sortTableTitle: [],
			isScroll: false,
			isShowTableLayer: false,
			dateTimeUpdate: [],
			isActiveCode: '#',
			tbTitleWidth:{},			
    },
    filters: {
      date(time) {
        if (!time) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd HH:mm:ss')
      },
      text(val) {
        if (val == 'WFP') {
          return '待分派'
        }
        if (val == 'YFP') {
          return '已分派'
        }
      },
      formatUndefined: function(item) {
			  if (!item) return '--'
				if (typeof item == 'number') {
					if (!isNaN(item) && item.toString().length == 13) {
						return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
					};
				}
			  return item
			},
    },
    computed: {
      isAllselect() {
        let txt = true
        this.listObj.expansionProjs.some(item => {
          if (!item.isPrint) {
            txt = false
          }
        })
        return txt
      }
    },
    methods: {
      // 表头中是否全选方法
      isAllSelectP(item){
        if(this.selectedMulItem.sjIds.length == this.listObj.expansionProjs.length){
          this.selectedMulItem.sjIds = []
        }else{
          this.selectedMulItem.sjIds = []
          this.listObj.expansionProjs.map(item =>{
            this.selectedMulItem.sjIds.push(item.id)
          })
        }
      },
      // 单个选择
      selectDispatchItem(item){
        let num = this.selectedMulItem.sjIds.indexOf(item)
        if( num == -1){
          this.selectedMulItem.sjIds.push(item)
        }else{
          this.selectedMulItem.sjIds.splice(num,1)
        }
      },
      // 获取当前用户所在的岗位列表
      getUserPositions(){
        hlhttp.get({
          url: 'organization/user_positions',
          data:{show_suborg:'Y'},
          success: data => {
            this.positionList = data;
          }
        })
      },
      // 操作区分派按钮方法
      dispatchBusiness(id){
        this.selectedMulItem.sjIds.push(id);
        this.isShowPersonLayer = true;
        this.selectedMulItem.id = null
        this.selectedMulItem.name = null
        this.personList = []
        $('.org-name').html('请选择')
        $('.person-name').html('请选择')
      },
      closePersonLayer(){
        this.isShowPersonLayer = false;
        this.selectedMulItem.sjIds = []
        this.selectedMulItem.id = ''
        this.selectedMulItem.name = ''
      },
      singleItemSelectProject(item) {
        var that = this;
        hlhttp.get({
          url: 'organization/admin_position_users',
          data: {
            'position_id': item.positionId,
            'is_admin': item.isAdmin
          },
          success: data => {
            that.personList = data;
            that.selectedMulItem.name = ''
            that.selectedMulItem.id = '';
            that.$refs.DJR.innerHTML = '请选择'
          }
        })
      },
      singleItemSelectPerson(item) {
        this.selectedMulItem.id = item.userId;
        this.selectedMulItem.name = item.userName;
      },

      // 确定分派的方法
      confirmDispatchSingleItem(){
        if(!this.selectedMulItem.id){
          hl.toast('请选择对接人')
          return
        } 
        if(!this.selectedMulItem.sjIds.length){
          hl.toast('请选择项目')
          return
        } 
        hlhttp.put({
          url:'market/expansion_proj_assign',
          data:{expansion_proj_ids:this.selectedMulItem.sjIds.join(','),assignee_id:this.selectedMulItem.id,assignee_name:this.selectedMulItem.name},
          success:data => {
            hl.toast('分派成功')
            this.isShowPersonLayer = false;
            this.isShowSelector = false;
            this.selectedMulItem.sjIds = []
            this.selectedMulItem.id = ''
            this.selectedMulItem.name = ''
            this.listDt()
          }
        })
      },
      // 关于批量分派
      pro_all_dispatch() {
        this.isShowSelector = !this.isShowSelector
        this.personList = []
        this.selectedMulItem = {
          sjIds: [],
          id: '',
          name: ''
        }
        this.getUserPositions();
      },
       //去详情
       goTodetail(id) {
        hlUrlUtil.goTo('projectDetail', {
          'id': id,
          'ddtab': true,
          'from': 'assigin'
        }, true)
      },
      //项目管理tab
      resetTab() {
        this.listMenuArrActive = [];
        this.listDt()
      },
      
      selectStatus(item) {
        setTimeout(() => {
          this.listDt()
        }, 300)
        if (this.listMenuArrActive.indexOf(item.code) == -1) {
          this.listMenuArrActive.push(item.code)
          return
        }
        this.listMenuArrActive.splice(this.listMenuArrActive.indexOf(item.code), 1)
      },
      //获取渠道分类
      channelCateDt() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'SCTZ',
            config_name: 'SCTZ_CHANNEL_CATE',
            parent_dict_code: '#'
          },
          success: (data) => {
            this.channelCateArr = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      //获取渠道名称
      channelNameDt() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'SCTZ',
            config_name: 'SCTZ_CHANNEL_NAME',
            parent_dict_code: this.channelCategoryCode[0]
          },
          success: (data) => {
            this.channelNameArr = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      //选择渠道分类
      selectedCC (item) {
      	this.channelCategoryCode = [item[0].dictCode];
      	this.channelNameArr = [];
      	this.channelNameDt()
      },
      //选择渠道名称
      selectedCN (item) {
      	this.channelNameCode = [item[0].dictCode];
      },
      //输入对接人进行搜索
      onInputDJR: function(e) {
        if (!this.rperson.name) {
          if (!e.data) {
            this.rperson.name = '';
            this.getDataGroup()
            return
          };
          this.rperson.name = e.data;
        }
        this.getDataGroup()
      },
      //判断有没有ids
      ifrpersonIds: function() {
        if (!this.rperson.ids.length) {
          this.rperson.name = null
        }
      },
      //设置对接人name，获取id
      setRperson: function(name, id) {
        this.rperson.ids = [];
        this.rperson.name = name;
        this.rperson.ids.push(id)
        this.rperson.list = [];
      },
      //搜索负责人工作组组员列表
      getDataGroup: function() {
        this.rperson.ids = [];
        hlhttp.get({
          url: 'tenants/users/_search',
          data: {
            keyword: this.rperson.name || '#',
            first_order: 'Y'
          },
          success: (res) => {
            this.rperson.list = res;
            for (var i = 0; i < this.rperson.list.length; i++) {
              if (this.rperson.name.match(res[i])) {
                this.rperson.ids.push(res[i].id)
              }
            }
          }
        })
      },
      //关闭对接人
      blurRperson() {
        setTimeout(() => {
          this.rperson.list = []
        }, 100)
      },
      //展开收起
      openOffOn() {
        this.isExtenseFlag = !this.isExtenseFlag
      },
      //省
      provinceData() {
        hlhttp.get({
          url: 'sub_regions',
          data: {
            region_id: '1'
          },
          success: (data) => {
            this.provinceList = hlArrayUtil.replaceData(data, [{key: 'regionId', rKey: 'code'}]);
          }
        })
      },
      //设置省
      setProvince (data) {
      	this.provinceId = [data[0].regionId];
      	this.cityData()
      	this.areaList = [];
      },
      //市
      cityData() {
        hlhttp.get({
          url: 'sub_regions',
          data: {
            region_id: this.provinceId[0]
          },
          success: (data) => {
            this.cityList = hlArrayUtil.replaceData(data, [{key: 'regionId', rKey: 'code'}]);
          }
        })
      },
      setCity (data) {
      	this.cityId = [data[0].regionId];
      	this.areaData()
      },
      //区
      areaData() {
        hlhttp.get({
          url: 'sub_regions',
          data: {
            region_id: this.cityId[0]
          },
          success: (data) => {
            this.areaList = hlArrayUtil.replaceData(data, [{key: 'regionId', rKey: 'code'}]);
          }
        })
      },
      setArea (data) {
      	this.areaId = [data[0].regionId];
      },
      //市场拓展项目管理列表
      listDt() {
        hlhttp.get({
          url: 'market/expansion_proj_assign_search',
          data: {
            "keyword": this.keyword || '#', // 信息搜索(项目名称proj_name、联系人contact_name、联系人电话contact_phone_num、创建人creator_name)
            "assignee_id": this.rperson.ids.length ? this.rperson.ids.toString() : '#', // 对接人
            "province_id": this.provinceId.length ? this.provinceId[0] : '#',// 项目所在地：省份
            "city_id": this.cityId.length ? this.cityId[0] : '#',// 项目所在地：城市
            "district_id": this.areaId.length ? this.areaId[0] : '#',// 项目所在地：区县
            "channel_category_code": this.channelCategoryCode.length ? this.channelCategoryCode[0] : '#',// 渠道分类
            "channel_name_code": this.channelNameCode.length ? this.channelNameCode[0] : '#',// 渠道名称
            "assign_status": this.listMenuArrActive.length ? this.listMenuArrActive.toString() : '#', // 状态：意向,已关闭,转运营   逗号,连接
            "column": this.columns,
            "order": this.orders,
            "limit": this.limit[0], // 分页参数，一页显示数量
            "page": this.page + '' // 分页参数，页码
          },
          success: (data) => {
            data.expansionProjs.map(item => {
              item.iSselect = false
            })
            this.listObj = data;
            $("#page").initPage(data.totalPage, this.page, (n) => {
              if (this.page == n) {
                return
              }
              this.page = n;
              this.listDt();
            });
            this.listNumberDt()
          }
        })
      },
      //项目数量
      listNumberDt() {
        hlhttp.get({
          url: 'market/expansion_proj_assign_statistics',
          data: {
            "keyword": this.keyword || '#', // 信息搜索(项目名称proj_name、联系人contact_name、联系人电话contact_phone_num、创建人creator_name)
            "assignee_id": this.rperson.ids.length ? this.rperson.ids.toString() : '#', // 对接人
            "province_id": this.provinceId.length ? this.provinceId[0] : '#',// 项目所在地：省份
            "city_id": this.cityId.length ? this.cityId[0] : '#',// 项目所在地：城市
            "district_id": this.areaId.length ? this.areaId[0] : '#',// 项目所在地：区县

            "channel_category_code": this.channelCategoryCode.length ? this.channelCategoryCode[0] : '#',// 渠道分类
            "channel_name_code": this.channelNameCode.length ? this.channelNameCode[0] : '#',// 渠道名称
          },
          success: (data) => {
            this.listMenu.map(item => {
              switch (item.code) {
                case 'WFP':
                  item.num = data.WFPCount
                  break;
                case 'YFP':
                  item.num = data.YFPCount
                  break;
                default:
                  item.num = 0
                  break;
              }
            })
          }
        })
      },
      //新增
      add() {
        hlUrlUtil.goTo('marketAdd', {
          ddtab: true
        }, true)
      },
      //重置
      reset() {
        this.keyword = ''
        this.rperson.ids = [];
        this.rperson.name = [];
        this.provinceId = [];
        this.cityId = [];
        this.areaId = [];
				this.channelNameArr = []
        this.channelCategoryCode = []
        this.channelNameCode = [];
        this.listMenuArrActive = []
        this.columns = '#'
        this.orders = '#'
        this.isActiveCode = '',
        this.limit = ['10'];
        this.page = 1;
        this.listDt()
      },
     
     
      //翻页数量
      turnPage(item) {
        this.page = 1;
        this.limit = [item[0].code];
        this.listDt()
      },

      //更新时间
      sortBySTTime (item) {
        if(this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.listDt()
      },
      //获取自定义表头配置状态
			configTypeDt () {
				hlhttp.get({
					url: 'configure/customize_column_header/type',
					data: {module: 'SCTZ_XMFP'},
					success: (data) => {
						this.configType = data.configType;
						this.customizeHeaderDt()
					}
				})
			},			
			//获取自定义表头配置信息
			customizeHeaderDt () {
				hlhttp.get({
					url: 'configure/customize_column_header',
					data: {module: 'SCTZ_XMFP'},
					success: (data) => {		
						data.customConfigList.map(item => {
							item.seq = Number(item.seq)
							item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
								this.dateTimeUpdate.push(item.value)
							}
						})
						if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
              data.customConfigList.unshift({
                value : 'iSselect',
                name:'全选',
                baseFlag:'Y',
                isChecked:'N',
              })
						}
						if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
              data.customConfigList.unshift({
                value : 'iSselect',
                name:'全选',
                customShowFlag:'Y',
                isChecked:'N'
              })
						}
            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));	
         
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle.splice(0,1)
						this.tbTitleWidthCalculation()
					}
				})
			},	
			//宽度计算
			tbTitleWidthCalculation () {
				let w = 0, flag = false;
				this.headArr.map(item => {
					if (item.value == '序') {
						flag = true;
					}
				})
				w = this.headArr.length * 120 - 80;
				this.tbTitleWidth = {width: w+ 'px'}
			},
			//弹窗显示
			showTableLayer() {
				this.isShowTableLayer = true;
      },
			//关闭自定义表头弹窗
			closeTableLayer() {
        this.isShowTableLayer = false;
      },
			//简单完整配置切换
			selectTableType(type) {
        this.configType = type;
				this.changeTableType(type)
				this.updateConfigType()
      },
			//更新自定义表头配置状态
			updateConfigType () {
				hlhttp.put({
					url: 'configure/customize_column_header/type',
					data: {module: 'SCTZ_XMFP', config_type: this.configType},
					success: () => {
						this.configTypeDt()
					}
				})
			},
			//改变头部
			changeTableType (type) {
				if (type == 'JD' || type == 'WZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
				}
				if (type == 'PZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
				}
				this.tbTitleWidthCalculation()
			},
			//显示某个自定义标题
			selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
			//关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
			showhighLightTitleItem(el, i) {
				this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
				this.sortTableTitle[i].isActive = 'N'
      },
			//鼠标经过显示scroll
			showScroll() {
        this.isScroll = true;
      },
			//鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
			// 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
				this.sortTableTitle.map((item, index) => {
          if(item.name != '全选'){
            dataArr.push({
              "base_flag": item.baseFlag,
              "seq": item.seq,
              "custom_show_flag": item.customShowFlag,
              "custom_seq": index,
              "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
              "dict_code": item.dictCode,
              "config_type": item.configType,
              "name": item.name,
              "value": item.value,
              "union_table_part": item.unionTablePart,
              flex: item.flex,
              style_width: item.styleWidth,
              order_flag: item.orderFlag,
              order_name: item.orderName
            })
          }
				})
				hlhttp.put({
					url: 'configure/customize_column_header',
					data: {
						module: 'SCTZ_XMFP',
						custom_config: JSON.stringify(dataArr)
					},
					success: (data) => {
						hl.toast('操作成功')
						this.closeTableLayer()
						this.updateConfigType()						
					}
				})
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
    },
    mounted() {
      hlSelectUi()
      this.initSortable()
      this.provinceData()
      this.listDt()
      this.channelCateDt()
      this.listNumberDt()
      this.configTypeDt()
      this.getUserPositions()
      var _this = this;
			document.body.onclick = function () {
        _this.rperson.list = [];
      }
    }
  })
}())
